import React, { Component } from 'react'
import Header from "../components/all/header";
import Footer from "../components/all/footer";
import OneGoods from "../components/shoppingCart/one_goods";
import {SShoppingCar} from "../styled/shoppingCart"
import { apilink } from '../api/apilink';
export default class shoppingCar extends Component {
    constructor(props){
        super(props)
        this.state={
            cartInfo:"",
            totalsMoney:0,
        }
        this.jumpRouter = this.jumpRouter.bind(this)
    }
    componentWillMount(){
        // 获取购物车中的数据
        if(sessionStorage.getItem("userId")){
            let usp = new URLSearchParams();
            usp.append("userId",sessionStorage.getItem("userId"))
            apilink("/api/get_cart_data","post",usp).then((ok)=>{
                console.log(ok)
                this.setState({
                    cartInfo:ok.data
                },()=>{
                    console.log(this.state.cartInfo)
                })
            })
        }else{
            alert("您还未登录，请先登录");
            this.props.history.push("/login")
        }
    }
    updata=()=>{
        // this.forceUpdate();
        console.log("updata");
        this.componentWillMount()
        

    }
    cartData=()=>{
        return this.state.cartInfo.map((item,index)=>{
            return (
                <OneGoods FUtotals={this.totalsMoney} updata={this.updata} cartInfo={item}></OneGoods>
            )
        })
        console.log(this.state.cartInfo)
    }//bug 逆向传值 数据？？？？
    totalsMoney=(val)=>{
        this.setState({
            totalsMoney:0
        })
        console.log(val)
        // this.setState({
        //     totalsMoney:0
        // },()=>{
        //     let totalsMoney = val + this.state.totalsMoney
        //     this.setState({
        //         totalsMoney:totalsMoney
        //     },()=>{
        //         console.log(this.state.totalsMoney)
        //     })
        // })
        
    }
    //结算
    jumpRouter(){
        // 点击结算时，获取数据库中的最新数据,判断是否选中
        let usp = new URLSearchParams();
            usp.append("userId",sessionStorage.getItem("userId"))
            apilink("/api/get_cart_data","post",usp).then((ok)=>{
                console.log(ok)
                this.setState({
                    cartInfo:ok.data //数据更新完成之后，循环
                },()=>{
                    console.log(this.state.cartInfo)
                    let obj = [];
                    let num=0;
                    this.state.cartInfo.forEach((item,index)=>{
                        if(item.goodsChecked){
                            let date = new Date()
                            //时间
                            let nowdate = date.getFullYear()+"-"+date.getMonth()+1+"-"+date.getDate()+"- "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
                            console.log(date.getFullYear()+"-"+date.getMonth()+1+"-"+date.getDate()+"- "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()) ;
                            //请求
                            let usp = new URLSearchParams();
                                usp.append("userId",sessionStorage.getItem("userId"));
                                usp.append("listGoodsId",item.listGoodsId);
                                usp.append("listGoodsNum",item.listGoodsNum);
                                usp.append("totalsMoney",item.totalsMoney);
                                usp.append("date",nowdate);
                            apilink("/api/jiesuan_totals","post",usp).then((ok)=>{
                                //把刚存入的数据存到localhost里面
                                obj.push({"id":index,"date":nowdate,"userId":item.userId,"listGoodsId":item.listGoodsId,"listGoodsNum":item.listGoodsNum,"totalsMoney":item.totalsMoney,"mainImg":item.mainImg,"price":item.price,"productData":item.productData,"productInfo":item.productInfo,"title":item.title,"kind":item.kind,"color":item.color,"productNumber":item.productNumber})
                                console.log(ok);
                                localStorage.setItem("dingdan",JSON.stringify(obj));
                            }).catch((err)=>{
                                console.log(err)
                            })
                            
                        }else{
                            num++;
                        }
                    })
                    // console.log(obj)
                    // alert(1)
                    if(num === this.state.cartInfo.length){
                        alert("请至少选择一商品结算");
                        return
                    }
                    this.props.history.push("/orderForGoods")
                })
            })
        // this.componentWillMount();
    }
    render() {
        return (
            <div>
                <Header></Header>
                    <SShoppingCar>
                    <div className="shoppingCart">
                        <h5>我的购物袋</h5>
                    {this.state.cartInfo?this.cartData():""}
                    <div className="totals content">
                        {/* <h2>总计：</h2> */}
                        <button onClick={this.jumpRouter}>结算</button>
                    </div>
                    </div>
                    </SShoppingCar>
                <Footer></Footer>
            </div>
        )
    }
}
